<template>
    <div class="shopping-cart-wrap">

        <div style="z-index: 10"
             v-loading="cartLoading"
             element-loading-text="正在努力生成订单中！">
            <!--购物车-->
            <el-card class="box-card " shadow="hover" >

                <div slot="header" class="clearfix">
                    <div class="media-display" style=" display: flex;justify-content: space-between;">
                        <el-link :underline="false" style="font-size: 20px">购物车</el-link>
                        <el-button type="primary" size="small" @click="toOrder" icon="el-icon-s-order">查看订单</el-button>
                    </div>
                </div>
                <div class="clearfix">
                    <el-table
                            row-class-name="row-class"
                            show-overflow-tooltip="true"
                            ref="multipleTable"
                            :data="cartVoList"
                            :fit="true"
                            tooltip-effect="dark"
                            style="width: 100%"
                            @selection-change="handleSelectionChange">
                        <!--                    <el-table-column
                                                    type="index"
                                                    index="1">
                                            </el-table-column>-->
                        <el-table-column
                                type="selection"
                                width="55">
                        </el-table-column>
                        <el-table-column
                                label="图片"
                                width="150">
                            <template slot-scope="scope">
                                <img @click="$router.push(`/product/${scope.row.productId}`)"
                                     style="cursor: pointer"
                                     :src="prefix + scope.row.specsImg" width="80" height="80" alt="商品图片">
                            </template>
                        </el-table-column>
                        <el-table-column
                                prop="name"
                                label="商品名称"
                                width="200"
                                min-width="200"
                                show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                                prop="productSpecs"
                                label="规格"
                                width="250"
                                show-overflow-tooltip>
                            <template slot-scope="scope">
                                {{ scope.row.productSpecs | parseSpecs }}
                            </template>
                        </el-table-column>

                        <el-table-column
                                prop="price"
                                label="单价"
                                class-name="label-center"
                                width="100">
                        </el-table-column>
                        <el-table-column
                                prop="count"
                                label="数量"
                                class-name="label-center"
                                width="230">
                            <template slot-scope="scope">
                                <!--@change="handleChange"  :max=""-->
                                <el-button @click="decrease(scope.$index,$event.target)" :disabled="scope.row.count === 1" icon="el-icon-minus" size="medium" circle></el-button>

                                <el-input v-model="scope.row.count"
                                          style="width: 80px;margin: 0 5px"
                                          size="medium"
                                          :readonly="true" placeholder="请输入内容"></el-input>

                                <el-button @click="increase(scope.$index,$event.target)" icon="el-icon-plus" size="medium" circle></el-button>
                            </template>
                        </el-table-column>
                        <el-table-column
                                prop="totalPrice"
                                label="小计"
                                width="130">
                            <template slot-scope="scope">
                                {{ scope.row.price * scope.row.count }}
                            </template>
                        </el-table-column>
                        <el-table-column
                                label="操作">
                            <template slot-scope="scope">
                                <el-popconfirm
                                        confirm-button-text='是的'
                                        cancel-button-text='不了'
                                        icon="el-icon-info"
                                        icon-color="red"
                                        title="是否删除商品？"
                                        @confirm="remove(scope.$index)">
                                    <el-button slot="reference" size="small" type="danger">删除</el-button>
                                </el-popconfirm>
                            </template>

                        </el-table-column>

                    </el-table>
                    <div style="margin-top: 20px;margin-right: 50px;float: right;">
                        <el-popconfirm
                                confirm-button-text='是的'
                                cancel-button-text='不了'
                                icon="el-icon-info"
                                icon-color="red"
                                title="是否删除商品？"
                                @confirm="remove()">
                            <el-button slot="reference" type="danger" plain style="margin-right: 10px">删除选中</el-button>
                        </el-popconfirm>

                        <el-button @click="toggleSelection()">取消选择</el-button>
                    </div>
                </div>

            </el-card>

            <!--结算-->
            <el-card class="box-card " shadow="hover" style="margin: 20px 0">
                <div class="settlement">
                    <div>
                        <el-link :underline="false">
                            已选择了
                            <span style="font-size: 20px;color: chocolate">{{ totalCount }}</span>
                            件商品</el-link>
                    </div>

                    <div>
                        <el-link :underline="false" style="margin-right: 30px">
                            合计
                            <span style="font-size: 20px;color: chocolate">{{ totalPrice }}</span>
                            元
                        </el-link>
                        <el-button type="primary" @click="orderGenerate" plain icon="el-icon-shopping-bag-1">结算</el-button>
                    </div>
                </div>
            </el-card>
        </div>
    </div>

</template>

<script>
    import { getShoppingCart, removeCart, decrease, increase} from "@/api/cart";
    import { orderGenerateRequest} from "@/api/order";
    import settings from '@/settings'

    export default {
        name: "ShoppingCart",// 购物车页面
        data() {
            return {
                prefix : settings.prefix || 'https://mall-resource-bucket.oss-cn-hangzhou.aliyuncs.com',// 全局前缀
                cartLoading: false,
                removeList: [],// 要删除的 商品规格id 数组
                cartVoList: [],// 购物车信息
                selectedCart: [],// 被选中的购物车信息

            }
        },
        methods: {
            toOrder(){// 去订单页
                this.$router.push('/order')
            },
            orderGenerate(){// 生成订单
                this.cartLoading = true
                console.log(this.selectedCart)
                if (this.selectedCart.length === 0){
                    this.$notify.warning({title: '失败',message: "请选择商品"});
                    return;
                }
                orderGenerateRequest(this.selectedCart).then(response => {
                    console.log(response)
                    if (response.state === true) {
                        this.$confirm('订单生成成功，是否去支付?', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            this.$router.push({ path: `/orderDetail/${response.data.orderId}`,})
                        }).catch(() => {

                        });
                        this.$notify.success({title: '成功',message: response.message, duration: 1500});
                    }else{
                        this.$notify.warning({title: '失败',message: response.message, duration: 1500});
                    }
                }).finally(_=>{this.cartLoading = false})
            },
            toggleSelection(rows) {
                if (rows) {
                    rows.forEach(row => {
                        this.$refs.multipleTable.toggleRowSelection(row);
                    });
                } else {
                    this.$refs.multipleTable.clearSelection();
                }
            },
            handleSelectionChange(selection) {
                //this.removeList.length = 0;
                this.selectedCart = selection;
                console.log(" this.selectedCart = ", this.selectedCart)
            },
            remove(index){// 移除购物车商品
                console.log(index)
                if (index !== undefined){// 如果有下标，就下标否则删除多个
                    this.removeList.length = 0
                    this.removeList.push(this.cartVoList[index].specsId)
                }else {
                    this.selectedCart.forEach(item => {
                        this.removeList.push(item.specsId)
                    })
                }
                console.log(this.removeList)
                if (this.removeList.length === 0){
                    this.$notify.warning({title: '失败',message: "请选择要删除的商品"});
                    return;
                }
                removeCart({specsIdList: this.removeList}).then(response => {
                    console.log(response)
                    if (response.state === true) {
                        //this.init()
                        if (index !== undefined){
                            this.cartVoList.splice(index, 1)
                        }else {
                            this.cartVoList = this.cartVoList.filter(item => !this.removeList.includes(item.specsId))
                        }
                        this.$notify.success({title: '成功',message: response.message, duration: 1500});
                    }else{
                        this.$notify.warning({title: '失败',message: response.message, duration: 1500});
                    }
                })
            },
            decrease(index,event){// 减少数量
                console.log(this.cartVoList[index].count)
                console.log(this.cartVoList[index].specsId)

                decrease({ specsId: this.cartVoList[index].specsId }).then(response => {
                    console.log(response)
                    if (response.state === true) {
                        this.cartVoList[index].count -= 1
                        this.$notify.success({title: '成功',message: response.message, duration: 1500});
                    }else{
                        this.$notify.warning({title: '失败',message: response.message, duration: 1500});
                    }
                })
                this.eventBlur(event)
            },
            increase(index,event){// 增加数量
                console.log(this.cartVoList[index].count)
                console.log(this.cartVoList[index].specsId)

                increase({ specsId: this.cartVoList[index].specsId }).then(response => {
                    console.log(response)
                    if (response.state === true) {
                        this.cartVoList[index].count += 1
                        this.$notify.success({title: '成功',message: response.message, duration: 1500});
                    }else{
                        this.$notify.warning({title: '失败',message: response.message, duration: 1500});
                    }
                })
                this.eventBlur(event)
            },
            eventBlur(event){
                if(event.nodeName === 'SPAN' || event.nodeName === 'I'){event = event.parentNode;}event.blur();
            },
            init(){
                getShoppingCart().then(response => {
                    console.log(response)
                    if (response.state === true) {
                        this.cartVoList = response.data.cartVoList//保存产品信息
                        //this.$notify.success({title: '成功',message: response.message, duration: 1500});
                    }else{
                        this.$notify.warning({title: '失败',message: response.message, duration: 1500});
                    }
                })
            },
        },
        computed: {
            totalCount(){
                return this.selectedCart.length;
            },
            totalPrice(){
                let sum = 0;
                this.selectedCart.forEach((item)=>{
                    sum += (item.price * item.count)
                })
                return sum;
            }
        },
        filters: {
            parseSpecs(specs){// 解析规格
                let specsObj = JSON.parse(specs);
                let str = "";
                Object.keys(specsObj).forEach((key)=>{
                    str += specsObj[key] + " "
                })
                return str
            }
        },
        beforeMount(){

        },
        mounted(){
            this.init()
        },
    }
</script>

<style scoped>
    .shopping-cart-wrap{
        width: 70vw;
        margin: 0 auto;
    }
    >>>.el-input__inner{
        text-align: center;
    }

    >>>.label-center{
        text-align: center;
    }
    >>>.row-class{
        height: 60px;
        font-size: 20px;
    }

    .settlement{
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: baseline;
    }

    .clearfix:before,
    .clearfix:after {
        display: table;
        content: "";
    }
    .clearfix:after {
        clear: both
    }

    .box-card {
    }

</style>
